using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;

namespace HappySprite.Simulation
{
    public static class CircleCircleAlgorithm
    {
        public static bool DetectCollision(CollisionEventArgs e)
        {
            Circle thisCircle = (Circle)e.This.CollisionShape;
            Circle otherCircle = (Circle)e.Other.CollisionShape;

            Vector2 p1 = e.This.Transform.Position;
            Vector2 p2 = e.Other.Transform.Position;
            Vector2 T = p2 - p1;

            // Uniform scaling only, get the largest scale factor
            float sf1 = Math.Max(e.This.Transform.Scale.X, e.This.Transform.Scale.Y);
            float sf2 = Math.Max(e.Other.Transform.Scale.X, e.Other.Transform.Scale.Y);

            float r1 = thisCircle.Radius * sf1;
            float r2 = otherCircle.Radius * sf2;

            // Simple collision check
            if (e.CollisionDetails == CollisionDetails.None)
                return T.LengthSquared() <= ((r1 + r2) * (r1 + r2));

            float tlen = T.Length();
            float depth = (r1 + r2) - tlen;

            // No intersection
            if (depth < 0f)
                return false;

            T.Normalize();
            e.Depth = depth;
            e.Normal = T;

            // Contact point data
            float k = 0.5f * (r1 - r2 + tlen);
            e.ContactPoint = p1 + e.Normal * k;

            // Witness points
            // pA = p1 - r1 * norm(T)
            // pB = p2 + r2 * norm(T) 

            return true;
        }
    }
}
